package templatemethod

import (
	"fmt"
	"time"
)

// OrderProcessor 订单处理接口
type OrderProcessor interface {
	ProcessOrder()
}

// OrderTemplate 订单模板
type OrderTemplate struct {
	OrderProcessor
	OrderId   string
	OrderType string
	CreateAt  time.Time
	Steps     []string
}

func NewOrderTemplate(orderProcessor OrderProcessor, orderId string, orderType string) *OrderTemplate {
	return &OrderTemplate{
		OrderProcessor: orderProcessor,
		OrderId:        orderId,
		OrderType:      orderType,
		CreateAt:       time.Now(),
		Steps:          make([]string, 0),
	}
}

func (t *OrderTemplate) ProcessOrder() {
	t.recordStep("订单处理开始")
	t.ProcessPayment()
	t.recordStep("订单处理结束")
	t.PrintProcessingSummary()
}

func (t *OrderTemplate) recordStep(step string) {
	t.Steps = append(t.Steps, fmt.Sprintf("%s: %s", time.Now().Format(time.TimeOnly), step))
}

func (t *OrderTemplate) PrintProcessingSummary() {
	fmt.Printf("\n===== 订单 %s 处理摘要 =====\n", t.OrderId)
	fmt.Printf("订单类型: %s\n", t.OrderType)
	fmt.Println("处理步骤:")
	for i, step := range t.Steps {
		fmt.Printf("%d. %s\n", i+1, step)
	}
	fmt.Println("=============================")
}

func (t *OrderTemplate) ProcessPayment() {
	// 由子类实现
}

// StandardOrderProcessor 标准订单处理器
type StandardOrderProcessor struct {
	*OrderTemplate
}

func NewStandardOrderProcessor(orderId string) *StandardOrderProcessor {
	processor := &StandardOrderProcessor{}
	processor.OrderTemplate = NewOrderTemplate(processor, orderId, "普通商品订单")
	return processor
}

func (s *StandardOrderProcessor) ProcessPayment() {
	fmt.Println("标准订单支付处理")
	s.recordStep("处理普通订单支付（立即扣款）")
}

// PreorderProcessor 预订单处理器
type PreorderProcessor struct {
	*OrderTemplate
	releaseDate time.Time
}

func NewPreorderProcessor(orderId string, releaseDate time.Time) *PreorderProcessor {
	processor := &PreorderProcessor{releaseDate: releaseDate}
	processor.OrderTemplate = NewOrderTemplate(processor, orderId, "预售订单")
	return processor
}

func (p *PreorderProcessor) ProcessPayment() {
	fmt.Println("预订单支付处理")
	p.recordStep("处理预售支付（预授权，发货时扣款）")
}